import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:secend_flutter/bean/travel_model_bean.dart';
import 'package:secend_flutter/dao/tao_ean.dart';
import 'package:secend_flutter/dao/travel_dao.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:secend_flutter/define_widget/webview_widget.dart';
const TRAVEL_URL =
    'https://m.ctrip.com/restapi/soa2/16189/json/searchTripShootListForHomePageV2?_fxpcqlniredt=09031014111431397988&__gw_appid=99999999&__gw_ver=1.0&__gw_from=10650013707&__gw_platform=H5';
const PAGE_SIZE=10;
class TravelListPage extends StatefulWidget {
  String? travelUrl;
  String groupChannelCode;
  Map params;

  TravelListPage(
      {Key? key,
      this.travelUrl,
      required this.groupChannelCode,
      required this.params})
      : super(key: key);

  @override
  _TravelListPageState createState() => _TravelListPageState();
}

class _TravelListPageState extends State<TravelListPage>
with AutomaticKeepAliveClientMixin{
  List<TravelItem> _travelItems = [];
  int pageIndex = 1;
  final ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    _getList();
    _scrollController.addListener(() {
      if(_scrollController.position.pixels==
      _scrollController.position.maxScrollExtent){
        _getList(loadMore:true);
      }
    });
  }


  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _getList({loadMore=false}) {
    if(loadMore){
      pageIndex++;
    }else{
      pageIndex=1;
    }
    TravelDao.fetch(widget.travelUrl ?? TRAVEL_URL, widget.params,
            widget.groupChannelCode, pageIndex,PAGE_SIZE)
        .then((TravelItemModel itemModel) {
        setState(() {
          List<TravelItem> items=_filterItem(itemModel.resultList);
          if(_travelItems.isNotEmpty){
            _travelItems.addAll(items);
          }else{
            _travelItems=items;
          }
        });
    });
  }

  List<TravelItem> _filterItem(List<TravelItem>? resultList) {
    if(resultList==null){
      return [];
    }
    List<TravelItem> items=[];
    resultList.forEach((element) {
      if(element.article!=null){
        items.add(element);
      }
    });
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        onRefresh: _handleRefresh,
      child:StaggeredGridView.countBuilder(
      padding: const EdgeInsets.only(top: 0),
      controller:_scrollController ,
      crossAxisCount: 4,
      mainAxisSpacing: 4,
      crossAxisSpacing: 4,
      itemCount: _travelItems.length,
      itemBuilder: (BuildContext context, int index) {
        return TravelItemWidget(_travelItems[index], index);
      }, staggeredTileBuilder: (int index) => const StaggeredTile.fit(2),
    ));
  }


  Future<void> _handleRefresh() async {
    _getList();
  }

  @override
  bool get wantKeepAlive =>true;
}

class TravelItemWidget extends StatelessWidget {
   TravelItem travelItem;
   int index;

   TravelItemWidget(this.travelItem, this.index);

   @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        if(travelItem.article.urls.length>0){
          Tiaboon.push(context, MyWebView(
            url: travelItem.article.urls[0].h5Url,
            title: '详情',
          ));
        }
      },
      child: Card(
        child: PhysicalModel(
          color: Colors.transparent,
          clipBehavior:Clip.antiAlias ,
          borderRadius: BorderRadius.circular(6),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _Image(context),
              Container(
                padding: const EdgeInsets.fromLTRB(4, 4, 4, 4),
                child: Text(
                  travelItem.article.articleTitle,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(fontSize: 15,color: Colors.black),
                ),
              ),
              _infoText()
            ],
          ),
        ),
      ),
    );
  }

  _Image(BuildContext context) {
    return Stack(
      children: [
        Image.network(travelItem.article.images[0].dynamicUrl),
        Positioned(
        bottom: 8,
        left: 8,
        child: Container(
          padding: const EdgeInsets.only(left: 5,right: 5),
          decoration: BoxDecoration(
            color: Colors.black45,
            borderRadius: BorderRadius.circular(5)
          ),
          child: Row(
            children: [
               Container(
                  padding: const EdgeInsets.only(right: 3),
                  child: const Icon(
                    Icons.location_on,
                    color: Colors.white,
                    size: 12,
                  )),
              LimitedBox(
                maxWidth: 130,
                child: Text(
                  _poiName(),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(color: Colors.white, fontSize: 12),
                ),
              )
            ],
          ),
        ))
      ],
    );
  }

  _infoText() {
    return Container(
      padding: const EdgeInsets.fromLTRB(6, 0, 6, 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: <Widget>[
              PhysicalModel(
                color: Colors.transparent,
                clipBehavior: Clip.antiAlias,
                borderRadius: BorderRadius.circular(12),
                child: Image.network(
                  travelItem.article.author?.coverImage?.dynamicUrl ?? "",
                  width: 24,
                  height: 24,
                ),
              ),
              Container(
                padding: const EdgeInsets.all(5),
                width: 90,
                child: Text(
                  travelItem.article.author?.nickName ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(fontSize: 12),
                ),
              )
            ],
          ),
          Row(
            children: <Widget>[
              const Icon(
                Icons.thumb_up,
                size: 14,
                color: Colors.grey,
              ),
              Padding(
                padding: const EdgeInsets.only(left: 3),
                child: Text(
                  travelItem.article.likeCount.toString(),
                  style: const TextStyle(fontSize: 10),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  String _poiName() {
    return travelItem.article.pois == null || travelItem.article.pois!.length == 0
        ? '未知'
        : travelItem.article.pois?[0]?.poiName ?? '未知';
  }
}

